package com.flute.icrawler.app.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 反射工具类
 * 
 */
public class ReflectUtil {

	/**
	 * 获取jar包中的所有类
	 * 
	 * @param jarFile
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static List<String> getJarClassNames(String jarFile)
			throws IOException {
		List<String> classNames = new ArrayList<String>();

		// 通过jarFile 和JarEntry得到所有的类
		JarFile jar = new JarFile(jarFile);
		Enumeration<JarEntry> e = jar.entries();
		while (e.hasMoreElements()) {
			JarEntry entry = (JarEntry) e.nextElement();
			// entry.getMethod()

			String sName = entry.getName();

			if (sName.endsWith(".class")) {

				String ppName = sName.replace("/", ".").replace(".class", "");
				classNames.add(ppName);

			}

		}
		return classNames;

	}

	public static List<Class> getJarClassBySuperClass(String jarFilePath,
			Class superClass) throws IOException, ClassNotFoundException {

		List<Class> classNames = new ArrayList<Class>();

		List<String> list = getJarClassNames(jarFilePath);
		for (int i = 0; i < list.size(); i++) {

			URL url1 = new URL("file:" + jarFilePath);
			URLClassLoader myClassLoader = new URLClassLoader(
					new URL[] { url1 }, Thread.currentThread()
							.getContextClassLoader());

			Class myClass = myClassLoader.loadClass(list.get(i));

			if (myClass.getSuperclass() == superClass) {
				classNames.add(myClass);
			}

		}

		return classNames;
	}

	public static Field[] getClassFields(Class classname) {
		Field[] fields = classname.getFields();
		return fields;

	}

	public static Field[] getClassFields(String jarFilePath, String classname)
			throws ClassNotFoundException, MalformedURLException {
		URL url1 = new URL("file:" + jarFilePath);
		URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url1 },
				Thread.currentThread().getContextClassLoader());

		Class myClass = myClassLoader.loadClass(classname);

		Field[] fields = myClass.getFields();
		return fields;

	}

	public static void main(String[] args) {

		String jarFilePath = "E://icrawler.jar";

		try {

			Field[] fields = ReflectUtil
					.getClassFields(jarFilePath,
							"com.flute.icrawler.app.processor.check.CheckConfigProcessor");
			for (int j = 0; j < fields.length; j++) {
				System.out.println("field:" + fields[j].getName() + ":"
						+ fields[j].getType().getCanonicalName());
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

}
